/*

Modified by Tan Shun 2020

Original file form https://github.com/docker/engine/blob/master/daemon/logger/jsonfilelog/read.go

Copyright 2013-2018 Docker, Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package log

import (
	"bytes"
	"context"
	"encoding/json"
	"errors"
	"github.com/docker/docker/pkg/tailfile"
	"github.com/jpillora/filenotify"
	"gopkg.in/fsnotify.v1"
	"io"
	"os"
)

func tailFile(f *os.File, logWatcher *Watcher, tail int, since int64) {
	var reader io.Reader
	reader = f
	if tail > 0 {
		ls, err := tailfile.TailFile(f, tail)
		if err != nil {
			logWatcher.Err <- err
			return
		}
		reader = bytes.NewBuffer(bytes.Join(ls, []byte("\n")))
	}
	dec := json.NewDecoder(reader)
	l := &Entry{}
	for {
		msg, err := decodeLogLine(dec, l)
		if err != nil {
			if err != io.EOF {
				logWatcher.Err <- err
			}
			return
		}
		if msg.LogTime < since {
			continue
		}
		logWatcher.Msg <- msg
	}
}

func decodeLogLine(dec *json.Decoder, l *Entry) (*Entry, error) {
	if err := dec.Decode(l); err != nil {
		return nil, err
	}
	var msg = &Entry{
		LogTime: l.LogTime,
		Line:    l.Line,
	}
	return msg, nil
}

func watchFile(name string) (filenotify.FileWatcher, error) {
	fileWatcher := filenotify.New()
	if err := fileWatcher.Add(name); err != nil {
		fileWatcher.Close()
		fileWatcher = filenotify.NewPollingWatcher()

		if err := fileWatcher.Add(name); err != nil {
			fileWatcher.Close()
			return nil, err
		}
	}
	return fileWatcher, nil
}

// watch log file to follow
func followLogs(file *os.File, logWatcher *Watcher, since int64) {
	dec := json.NewDecoder(file)
	line := &Entry{}

	filename := file.Name()
	// 监听文件
	fileWatcher, err := watchFile(filename)
	if err != nil {
		logWatcher.Err <- err
		return
	}
	defer func() {
		file.Close()
		fileWatcher.Remove(filename)
		fileWatcher.Close()
	}()
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	go func() {
		select {
		case <-logWatcher.closeNotifier:
			fileWatcher.Remove(filename)
			cancel()
		case <-ctx.Done():
			return
		}
	}()

	var retries int
	errRetry := errors.New("retry")
	errDone := errors.New("done")
	waitRead := func() error {
		select {
		case e := <-fileWatcher.Events():
			switch e.Op {
			case fsnotify.Write:
				dec = json.NewDecoder(file)
				return nil
			case fsnotify.Rename, fsnotify.Remove:
				select {
				case <-ctx.Done():
					return errDone
				}
			}
			return errRetry
		case err := <-fileWatcher.Errors():
			// Something happened, let's try and stay alive and create a new watcher
			if retries <= 5 {
				fileWatcher.Close()
				fileWatcher, err = watchFile(filename)
				if err != nil {
					return err
				}
				retries++
				return errRetry
			}
			return err
		case <-ctx.Done():
			return errDone
		}
	}

	handleDecodeErr := func(err error) error {
		if err == io.EOF {
			for err := waitRead(); err != nil; {
				if err == errRetry {
					// retry the waitRead
					continue
				}
				return err
			}
			return nil
		}
		// try again because this shouldn't happen
		if _, ok := err.(*json.SyntaxError); ok && retries <= maxJSONDecodeRetry {
			dec = json.NewDecoder(file)
			retries++
			return nil
		}
		// io.ErrUnexpectedEOF is returned from json.Decoder when there is
		// remaining data in the parser's buffer while an io.EOF occurs.
		// If the json logger writes a partial json log entry to the disk
		// while at the same time the decoder tries to decode it, the race condition happens.
		if err == io.ErrUnexpectedEOF && retries <= maxJSONDecodeRetry {
			// 如果发生这个错误, 就是 decode 失败了
			// 如果原来的 dec 里面还有值就将原来的和文件重新组合成一个 MultiReader
			// 作用就是将两个 buffer 连接在一起,
			// 再读的时候就首先第一个 Buffer 里面读, 然后再从文件读
			reader := io.MultiReader(dec.Buffered(), file)
			dec = json.NewDecoder(reader)
			retries++
			return nil
		}
		return err
	}

	// follow 的主循环
	for {
		msg, err := decodeLogLine(dec, line)
		if err != nil {
			if err := handleDecodeErr(err); err != nil {
				if err == errDone {
					return
				}
				// we got an unrecoverable error, so return
				logWatcher.Err <- err
				return
			}
			// ready to try again
			continue
		}

		retries = 0 // reset retries since we've succeeded
		if msg.LogTime < since {
			continue
		}

		select {
		case logWatcher.Msg <- msg:
		case <-ctx.Done():
			logWatcher.Msg <- msg
			for {
				msg, err := decodeLogLine(dec, line)
				if err != nil {
					return
				}
				if since < msg.LogTime {
					continue
				}
				logWatcher.Msg <- msg
			}
		}
	}

}
